package service

import (
	"errors"
	"github.com/gorilla/websocket"
	"gorm.io/gorm"
	"main/app"
	"main/config"
	"main/internal/model"
	"main/internal/pkg/code"
	"main/internal/pkg/ks"
	"main/internal/pkg/wss"
	"net/http"
	"strconv"
	"strings"
	"sync"
)

var mutex sync.Mutex

var Client = make(map[string]*websocket.Conn)

var SysLiveMsgService = sysLiveMsgService{}

// sysLiveMsgService 业务层
type sysLiveMsgService struct {
}

func (t sysLiveMsgService) db() *gorm.DB {
	return app.Db
}

// Create 创建记录
func (t sysLiveMsgService) Create(v model.SysLiveMsg, uid uint) (model.SysLiveMsg, error) {
	v.CreateBy = uid
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Create(&v)
	if dbres.Error != nil {
		return model.SysLiveMsg{}, dbres.Error
	}
	return v, nil
}

// CreateList 批量创建记录
func (t sysLiveMsgService) CreateList(v []model.SysLiveMsg, uid uint) ([]model.SysLiveMsg, error) {
	for k, _ := range v {
		//v[k].AdminExpiration = time.Now().AddDate(10, 0, 0)
		v[k].CreateBy = uid
	}
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Create(&v)
	if dbres.Error != nil {
		return []model.SysLiveMsg{}, dbres.Error
	}
	return v, nil
}

// Delete 根据ID删除记录
func (t sysLiveMsgService) Delete(v uint, uid uint) (uint, error) {
	t.db().Table(model.SysLiveMsg{}.TableName()).Where("id = ?", v).Update("delete_by", uid)
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Where("id = ?", v).Delete(&v)
	if dbres.Error != nil {
		return v, dbres.Error
	}
	return v, nil
}

// DeleteList 根据ID删除记录
func (t sysLiveMsgService) DeleteList(v []uint, uid uint) ([]uint, error) {
	t.db().Table(model.SysLiveMsg{}.TableName()).Where("id IN (?)", v).Update("delete_by", uid)
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Where("id IN (?)", v).Delete(&v)
	if dbres.Error != nil {
		return v, dbres.Error
	}
	return v, nil
}

// Get 根据ID查询
func (t sysLiveMsgService) Get(v uint, lang string) (model.SysLiveMsg, error) {
	var data model.SysLiveMsg
	var count int64
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Where("id = ?", v).Find(&data).Count(&count)
	if count == 0 {
		err := errors.New(code.GetMsg(code.RecordNotExist, lang))
		return model.SysLiveMsg{}, err
	}
	if dbres.Error != nil {
		return data, dbres.Error
	}
	return data, nil
}

// GetList 批量查询
func (t sysLiveMsgService) GetList(page, size int, kw string, ids []uint, id uint, dateForm, dateTo, status, lang string) ([]model.SysLiveMsg, error, int64) {
	var data []model.SysLiveMsg
	var count int64
	limit := size
	offset := size * (page - 1)
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Count(&count)
	dbres = t.db().Table(model.SysLiveMsg{}.TableName())
	if kw != "" {
		dbres = dbres.Where("admin_email LIKE ?", "%"+kw+"%")
	}
	if id != 0 {
		dbres = dbres.Where("id = ?", id)
	}
	if len(ids) > 0 {
		if ids[0] != 0 {
			dbres = dbres.Where("id IN (?)", ids)
		}
	}
	if dateForm != "" {
		dbres = dbres.Where("created_at >= ?", dateForm)
	}
	if dateTo != "" {
		dbres = dbres.Where("created_at <= ?", dateTo)
	}
	if status != "" {
		dbres = dbres.Where("status = ?", status)
	}
	if page != 0 {
		dbres = dbres.Limit(limit).Offset(offset)
	}
	dbres.Find(&data).Count(&count)
	if count == 0 {
		err := errors.New(code.GetMsg(code.RecordNotExist, lang))
		return []model.SysLiveMsg{}, err, count
	}
	if dbres.Error != nil {
		return data, dbres.Error, count
	}
	return data, nil, count
}

// UpdateData 根据ID更新数据
func (t sysLiveMsgService) UpdateData(v model.SysLiveMsg, uid uint) (model.SysLiveMsg, error) {
	var data model.SysLiveMsg
	v.UpdateBy = uid
	dbres := t.db().Table(model.SysLiveMsg{}.TableName()).Save(&v)
	if dbres.Error != nil {
		return data, dbres.Error
	}
	return data, nil
}

func (t sysLiveMsgService) Ws(w http.ResponseWriter, r *http.Request, token string) {
	//先查询是否绑定过直播间
	var bindRes ks.BindRoomRes
	var liveStatus ks.QueryStatusRes
	var giftTop ks.GiftTopRes
	var giftList []string

	liveStatus = ks.QueryLiveStatus(config.Cfg.Ksgame.Appid, config.Cfg.Ksgame.Appsecret, token)
	if liveStatus.TaskStatus != 1 {
		//开始绑定直播间
		bindRes = ks.BindRoom(config.Cfg.Ksgame.Appid, config.Cfg.Ksgame.Appsecret, token, "123456")
		if bindRes.Result != 1 {
			return
		}
		//bindRes.UserInfo.UserName
		//bindRes.UserInfo.AuthorOpenId
		//bindRes.UserInfo.HeadUrl
	}
	//开始礼物置顶
	//从数据库里边查询需要的礼物列表
	list, _, _ := SysGiftService.GetList(1, 30, "", []uint{}, 0, "", "", "1", "")
	for _, v := range list {
		if v.GiftType == "快手" && v.Status == "1" {
			giftList = append(giftList, strconv.FormatInt(v.GiftId, 10))
		}
	}
	giftTop = ks.GiftTop(config.Cfg.Ksgame.Appid, config.Cfg.Ksgame.Appsecret, token, strings.Join(giftList, ","), nil)
	if giftTop.Result != 1 {
		return
	}
	//绑定成功 然后记录到数据库
	SysUserLiveListService.Create(model.SysUserLiveList{
		UserName: bindRes.UserInfo.UserName,
		UserId:   bindRes.UserInfo.AuthorOpenId,
		HeadUrl:  bindRes.UserInfo.HeadUrl,
		RoomCode: token,
	}, 0)
	wss.WsHandler(w, r, ksOnOpen, ksOnError, ksOnClose, ksOnMsg, token)
}

// 接受快手弹幕数据并解析专用
func ksOnOpen(conn *websocket.Conn, roomCode string) {
	Client[roomCode] = conn
}

func ksOnMsg(conn *websocket.Conn, msg []byte, msgtype int, roomCode string) {

}

func ksOnError(err error) {

}
func ksOnClose(conn *websocket.Conn, err error, roomCode string) {
	delete(Client, roomCode)
}

func (t sysLiveMsgService) GiftHandlerMsg(msg ks.GiftSendMsg) {
	for _, v := range msg.Data.Payload {
		SendWsMsg(msg.Data.RoomCode, DmMsg{
			Type:  4,
			Uid:   v.UserInfo.UserId,
			Name:  v.UserInfo.UserName,
			Url:   v.UserInfo.HeadUrl,
			Msg:   "送礼",
			Gift:  v.GiftName,
			Num:   v.GiftCount,
			Price: v.GiftUnitPrice,
		})
		//todo 记录到数据库
		t.Create(model.SysLiveMsg{
			LiveType:      "快手",
			LiveRoomId:    msg.Data.RoomCode,
			LiveUserName:  v.UserInfo.UserName,
			LiveUserUid:   v.UserInfo.UserId,
			LiveHeadUrl:   v.UserInfo.HeadUrl,
			LiveMessage:   "送礼",
			LiveGiftName:  v.GiftName,
			LiveGiftNum:   int64(v.GiftCount),
			LiveGiftPrice: int64(v.GiftUnitPrice),
		}, 0)
		//todo 记录到数据库
		SysUserListService.Create(model.SysUserList{
			UserName:    v.UserInfo.UserName,
			UserUid:     v.UserInfo.UserId,
			UserHeadUrl: v.UserInfo.HeadUrl,
		}, 0)
	}

}

func (t sysLiveMsgService) CommentHandlerMsg(msg ks.CommentSendMsg) {
	for _, v := range msg.Data.Payload {
		SendWsMsg(msg.Data.RoomCode, DmMsg{
			Type:  2,
			Uid:   v.UserInfo.UserId,
			Name:  v.UserInfo.UserName,
			Url:   v.UserInfo.HeadUrl,
			Msg:   v.Content,
			Gift:  "",
			Num:   0,
			Price: 0,
		})
		//todo 记录到数据库
		t.Create(model.SysLiveMsg{
			LiveType:      "快手",
			LiveRoomId:    msg.Data.RoomCode,
			LiveUserName:  v.UserInfo.UserName,
			LiveUserUid:   v.UserInfo.UserId,
			LiveHeadUrl:   v.UserInfo.HeadUrl,
			LiveMessage:   v.Content,
			LiveGiftName:  "",
			LiveGiftNum:   0,
			LiveGiftPrice: 0,
		}, 0)
		SysUserListService.Create(model.SysUserList{
			UserName:    v.UserInfo.UserName,
			UserUid:     v.UserInfo.UserId,
			UserHeadUrl: v.UserInfo.HeadUrl,
		}, 0)
	}
}

func (t sysLiveMsgService) LikeHandlerMsg(msg ks.LikeSendMsg) {
	for _, v := range msg.Data.Payload {
		SendWsMsg(msg.Data.RoomCode, DmMsg{
			Type:  3,
			Uid:   v.UserInfo.UserId,
			Name:  v.UserInfo.UserName,
			Url:   v.UserInfo.HeadUrl,
			Msg:   "点赞",
			Gift:  "",
			Num:   v.Count,
			Price: 0,
		})
		//todo 记录到数据库
		t.Create(model.SysLiveMsg{
			LiveType:      "快手",
			LiveRoomId:    msg.Data.RoomCode,
			LiveUserName:  v.UserInfo.UserName,
			LiveUserUid:   v.UserInfo.UserId,
			LiveHeadUrl:   v.UserInfo.HeadUrl,
			LiveMessage:   "点赞",
			LiveGiftName:  "",
			LiveGiftNum:   int64(v.Count),
			LiveGiftPrice: 0,
		}, 0)
		SysUserListService.Create(model.SysUserList{
			UserName:    v.UserInfo.UserName,
			UserUid:     v.UserInfo.UserId,
			UserHeadUrl: v.UserInfo.HeadUrl,
		}, 0)
	}
}

func (t sysLiveMsgService) FollowHandlerMsg(msg ks.FollowSendMsg) {
	for _, v := range msg.Data.Payload {
		SendWsMsg(msg.Data.RoomCode, DmMsg{
			Type:  5,
			Uid:   v.UserInfo.UserId,
			Name:  v.UserInfo.UserName,
			Url:   v.UserInfo.HeadUrl,
			Msg:   "关注",
			Gift:  "",
			Num:   0,
			Price: 0,
		})
		//todo 记录到数据库
		t.Create(model.SysLiveMsg{
			LiveType:      "快手",
			LiveRoomId:    msg.Data.RoomCode,
			LiveUserName:  v.UserInfo.UserName,
			LiveUserUid:   v.UserInfo.UserId,
			LiveHeadUrl:   v.UserInfo.HeadUrl,
			LiveMessage:   "关注",
			LiveGiftName:  "",
			LiveGiftNum:   0,
			LiveGiftPrice: 0,
		}, 0)
		SysUserListService.Create(model.SysUserList{
			UserName:    v.UserInfo.UserName,
			UserUid:     v.UserInfo.UserId,
			UserHeadUrl: v.UserInfo.HeadUrl,
		}, 0)
	}
}

func SendWsMsg(roomCode string, msg DmMsg) {
	mutex.Lock()
	Client[roomCode].WriteJSON(msg)
	mutex.Unlock()
}

type DmMsg struct {
	//1来了 2发言 3点赞 4送礼 5关注主播
	Type  int    `json:"type"`
	Uid   string `json:"uid"`
	Name  string `json:"name"`
	Url   string `json:"url"`
	Msg   string `json:"msg"`
	Gift  string `json:"gift"`
	Num   int    `json:"num"`
	Price int    `json:"price"`
}
